package com.njdf.servlet;

import com.njdf.entity.People;
import com.njdf.service.UserService;
import com.njdf.service.serviceImpl.UserServiceImpl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class LoginServlet extends javax.servlet.http.HttpServlet {
    @Override
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String verifyCode = request.getParameter("verifyCode");
        String session_img = (String) request.getSession().getAttribute("session_img");
        People people = new People(username, password);
        PrintWriter out = response.getWriter();
        UserService userService = new UserServiceImpl();
        People people1 = userService.queryByName(username);
//        System.out.println(people1);

        if (people1 != null) {
            List<People> peoples = userService.queryAll();
            String pwd = people1.getPassword();
            if (pwd != null && password != null && password != ""&&verifyCode!=null&&verifyCode!="") {
                if (pwd.equals(password)&&session_img.equalsIgnoreCase(verifyCode) ){
                    request.setAttribute("peoples", peoples);
                    request.getSession().setAttribute("people", username);
                    request.getRequestDispatcher("/success.jsp").forward(request, response);
                } else {
                    out.print("验证码或密码错误");
                    response.setHeader("refresh", "3;" + request.getContextPath() + "/index.jsp");
                }
            } else if (password == null || password == "") {
                out.print("不能为空，请重新登录");
                response.setHeader("refresh", "2;" + request.getContextPath() + "/index.jsp");
            }
        } else {
            out.print("不存在，请重新登录");
            response.setHeader("refresh", "2;" + request.getContextPath() + "/index.jsp");
        }
    }

    @Override
    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doPost(request, response);
    }
}
